/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.standardcloud.gateway.service;

import lombok.extern.slf4j.Slf4j;
import org.omg.CosNaming.NamingContextPackage.NotFound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import reactor.core.Disposable;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;

/**
 * @project-name:standard-cloud
 * @package-name:com.hyts.standardcloud.gateway.service
 * @author:LiBo/Alex
 * @create-date:2020-01-05 22:24
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
@Service
public class RefreshRouteService implements ApplicationEventPublisherAware,DaoRouteService {


    @Autowired
    private RouteDefinitionRepository routeDefinitionRepository;


    private ApplicationEventPublisher publisher;


    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    /**
     * 添加路由
     * @param routeDefinition
     * @return
     */
    @Override
    public boolean addRoute(RouteDefinition routeDefinition) {
        try {
            Disposable result = routeDefinitionRepository.save(Mono.justOrEmpty(routeDefinition)).subscribe(System.out::println);
            publisher.publishEvent(new RefreshRoutesEvent(this));
            return result.isDisposed();
        } catch (Exception e) {
            log.error("路由保存失败!",e);
            return false;
        }
    }

    @Override
    public boolean editRoute(RouteDefinition routeDefinition) {
        try {
            removeRoute(routeDefinition);
            Disposable result = routeDefinitionRepository.save(Mono.justOrEmpty(routeDefinition)).subscribe(System.out::println);
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return result.isDisposed();
        } catch (Exception e) {
            log.error("路由保存失败!",e);
            return false;
        }
    }

    @Override
    public boolean removeRoute(RouteDefinition routeDefinition) {
        try {
            routeDefinitionRepository.
                    delete(Mono.just(routeDefinition.getId())).
                    then(Mono.defer(()->Mono.justOrEmpty(ResponseEntity.ok().build()))).
                    onErrorResume(error -> (error instanceof NotFoundException),
                            error2-> Mono.just(ResponseEntity.notFound().build()));
        } catch (Exception e) {
            log.error("删除路由信息",e);
            return false;
        }
        return true;
    }

    @Override
    public Mono<List<RouteDefinition>> searchRoute(String searchKey) {
        try {
            return routeDefinitionRepository.getRouteDefinitions().collectList().take(Duration.ofMillis(2000L));
        } catch (Exception e) {
            log.error("查询数据路由信息失败!",e);
            return Mono.empty();
        }
    }
}
